Understanding Computer Programming

Osher Lifelong Learning Institute
University of Illinois, Urbana-Champaign

Scott Badman, Instructor


Topic: Prime implemented in HTML and JavaScript

March 3, 2016


Number:



Code that implements the Prime Algorithm above:

<html>
<head>

<script type="text/javascript">

     function modulo(number, divisor)
     {
         var intermediate;
         var remainder;
         intermediate = number;

         while (intermediate >= divisor)
         {
             intermediate = intermediate - divisor;
         }

         remainder = intermediate;

         return remainder;
     }

</script>


<script type="text/javascript">

     function determineIfPrime(number)
     {
         var divisor;
         var remainder;
         var prime;

         if (remainder == 0)
             return prime;

         prime = true;

         divisor = 2;
         while (divisor < number)
         {
             remainder = modulo(number, divisor);

             if (remainder == 0)
                 prime = false;

             divisor = divisor + 1;
         }

         return prime;
     }

</script>

<script type="text/javascript">
     function isAPrime()
     {
         var number = document.getElementById('numberInput').value;
         var prime;

         if (number >= 0 && number <= 1000000)
         {
             prime = determineIfPrime(number);

             if (prime == true)
                     document.getElementById("output").innerHTML = number + " is a prime.";
             else
                 document.getElementById("output").innerHTML = number + " is not a prime.";
         }
         else
             document.getElementById("output").innerHTML = "Number out of range";
     }

</script>

</head>

<body>

<p>
<font color="#000000" face="Arial" size="3">

Number:
<input id='numberInput' type='integer'></input>

<button id='runModulo' onclick='isAPrime()'>
Prime?
</button>

</font>
</p>

</body>
</html>


Understanding Computer Programming

Osher Lifelong Learning Institute
University of Illinois, Urbana-Champaign

Scott Badman, Instructor